package com.yoyo.yyadsdk.util;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;


import java.util.List;

public class ShortcutUtil {

    public static void createShortcut(Context context, Class<?> target, String strTitle, int resourceid) {
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, strTitle);
        shortcut.putExtra("duplicate", false);// 设置是否重复创建
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClass(context, target);// 设置第一个页面
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        ShortcutIconResource iconRes = ShortcutIconResource.fromContext(context, resourceid);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
        context.sendBroadcast(shortcut);
    }

    public static void createShortcut(Context context, String strClass, String strTitle, String strInstruction, String strPkgList, String strPushid, Bitmap bitmap) {

        // ANDROID 5.1之后创建快捷方式需要用INTENT，不能用COMPOMENT
        if (getSDKVersionInt() < 22) {
            ComponentName componentName = new ComponentName(context.getPackageName(), strClass);
            Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, strTitle);
            shortcutIntent.putExtra("duplicate", false); // 是否允许重复创建
            Intent intent = new Intent(Intent.ACTION_MAIN).setComponent(componentName);
            intent.putExtra("instruction", strInstruction);
            intent.putExtra("title", strTitle);
            intent.putExtra("pushid", strPushid);
            intent.putExtra("pkglist", strPkgList);
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
            if (bitmap != null) {
                shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
                context.sendBroadcast(shortcutIntent);
            }

        } else {
            Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, strTitle);
            shortcutIntent.putExtra("duplicate", false); // 是否允许重复创建

            Intent intent = new Intent();
            intent.setAction("com.yoyo.yyadsdk.activity.AdWebViewActivity");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.putExtra("instruction", strInstruction);
            intent.putExtra("title", strTitle);
            intent.putExtra("pushid", strPushid);
            intent.putExtra("pkglist", strPkgList);
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
            if (bitmap != null) {
                shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
                context.sendBroadcast(shortcutIntent);
            }
        }
    }

    // 为第三方应用创建快捷方式
    public static boolean createAppShortcut(Context context, String strTitle, Bitmap bitmap, String strIntent, String strCategory, String strPackage, String strActivity, String strStartParam) {

        // ANDROID 5.1之后创建快捷方式需要用INTENT，不能用COMPOMENT
        if (getSDKVersionInt() > 21 && TextUtils.isEmpty(strIntent)) {
            return false;
        }

        if (!TextUtils.isEmpty(strIntent)) {
            Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, strTitle);
            shortcutIntent.putExtra("duplicate", false); // 是否允许重复创建

            Intent intent = new Intent();
            intent.setAction(strIntent);

            if (!TextUtils.isEmpty(strCategory)) {
                intent.addCategory("android.intent.category.DEFAULT");
            } else {
                intent.addCategory(strCategory);
            }

            if (!TextUtils.isEmpty(strPackage)) {
                intent.setPackage(strPackage);
            }

//            StartAppUtils.parseActivityParams(strStartParam, intent);

            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
            if (bitmap != null) {
                shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
                context.sendBroadcast(shortcutIntent);
            }


            return true;

        } else if (!TextUtils.isEmpty(strPackage) && !TextUtils.isEmpty(strActivity)) {
            ComponentName componentName = new ComponentName(strPackage, strActivity);
            Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, strTitle);
            shortcutIntent.putExtra("duplicate", false); // 是否允许重复创建
            Intent intent = new Intent(Intent.ACTION_MAIN).setComponent(componentName);
//            StartAppUtils.parseActivityParams(strStartParam, intent);
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
            if (bitmap != null) {
                shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
                context.sendBroadcast(shortcutIntent);

                return true;

            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    // 判读是否已经存在快捷方式
    public static boolean isExistShortCut(Context context, String strTitle) {
        // boolean isInstallShortcut = false;
        // final ContentResolver cr = context.getContentResolver();
        // //
        // 本人的2.2系统是”com.android.launcher2.settings”,网上见其他的为"com.android.launcher.settings"
        // final String AUTHORITY = "com.android.launcher2.settings";
        // final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
        // "/favorites?notify=true");
        // Cursor c = cr.query(CONTENT_URI, new String[] { "title",
        // "iconResource" }, "title=?", new String[] { strTitle }, null);
        // if (c != null && c.getCount() > 0) {
        // isInstallShortcut = true;
        // }
        // return isInstallShortcut;

        String url = "";
        url = "content://" + getAuthorityFromPermission(context, "com.android.launcher.permission.READ_SETTINGS") + "/favorites?notify=true";
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse(url), new String[]{"title", "iconResource"}, "title=?", new String[]{strTitle.trim()}, null);
        if (cursor != null && cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        return false;
    }

    public static void addShortcutURL(Context context, String name, Uri uri, Bitmap bitmap, String pkgname, String strActivity) {
        Intent intentAddShortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);

        if (bitmap != null) {
            intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);

            Intent intentLauncher = new Intent();
            intentLauncher.setAction(Intent.ACTION_VIEW);
            intentLauncher.setData(uri);

            if (!TextUtils.isEmpty(pkgname)) {
                if (!TextUtils.isEmpty(strActivity)) {
                    intentLauncher.setClassName(pkgname, strActivity);
                } else {
                    intentLauncher.setPackage(pkgname);
                }
            }
            intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intentLauncher);
            context.sendBroadcast(intentAddShortcut);
        }

    }

    public static void deleteShortCut(Context context, String strClass, String shortcutName) {
        // Intent shortcut = new
        // Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
        // // 快捷方式的名称
        // shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
        // // 在网上看到到的基本都是一下几句，测试的时候发现并不能删除快捷方式。
        // // String appClass = activity.getPackageName()+"."+
        // // activity.getLocalClassName();
        // // ComponentName comp = new ComponentName( activity.getPackageName(),
        // // appClass);
        // // shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new
        // // Intent(Intent.ACTION_MAIN).setComponent(comp));
        // /** 改成以下方式能够成功删除，估计是删除和创建需要对应才能找到快捷方式并成功删除 **/
        // Intent intent = new Intent();
//        ComponentName componentName = new ComponentName(context.getPackageName(), strClass);
//        Intent intent = new Intent(Intent.ACTION_MAIN).setComponent(componentName);
//        // intent.setClass(activity, activity.getClass());
//        intent.setAction("android.intent.action.MAIN");
//        intent.addCategory("android.intent.category.LAUNCHER");
//        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
//        context.sendBroadcast(shortcut);

        ComponentName componentName = new ComponentName(context.getPackageName(), strClass);
        Intent shortcutIntent = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
        shortcutIntent.putExtra("duplicate", false); // 是否允许重复创建
//        Intent intent = new Intent(Intent.ACTION_MAIN)
        Intent intent = new Intent("com.dollkey.hdownload.MAIN")
                .setComponent(componentName);
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        context.sendBroadcast(shortcutIntent);
    }

    private static String getAuthorityFromPermission(Context context, String permission) {
        if (permission == null)
            return null;
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs != null) {
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission))
                            return provider.authority;
                        if (permission.equals(provider.writePermission))
                            return provider.authority;
                    }
                }
            }
        }
        return null;
    }

    public static int getSDKVersionInt() {
        try {
            return Build.VERSION.SDK_INT;
        } catch (Exception e) {
            return 0;
        }
    }
}
